package info.batcloud.fanli.core.service.impl;

import info.batcloud.fanli.core.dto.CollectionSourceAddDTO;
import info.batcloud.fanli.core.dto.CollectionSourceDTO;
import info.batcloud.fanli.core.dto.CollectionSourceUpdateDTO;
import info.batcloud.fanli.core.entity.CollectionSource;
import info.batcloud.fanli.core.enums.CollectionSourceStatus;
import info.batcloud.fanli.core.repository.CollectionSourceRepository;
import info.batcloud.fanli.core.service.CollectionSourceService;
import org.springframework.beans.BeanUtils;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import javax.inject.Inject;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class CollectionSourceServiceImpl implements CollectionSourceService {

    @Inject
    private CollectionSourceRepository collectionSourceRepository;

    @Override
    public List<CollectionSourceDTO> findAll() {
        return convertToDto(collectionSourceRepository
                .findByStatusNot(CollectionSourceStatus.DELETED, new Sort(Sort.Direction.DESC,"id")));
    }

    @Override
    public void saveCollectionSource(CollectionSourceAddDTO source) {
        CollectionSource cs = new CollectionSource();
        BeanUtils.copyProperties(source, cs);
        cs.setCreateTime(new Date());
        if(cs.getStatus() == CollectionSourceStatus.STARTED) {
            cs.setStartTime(new Date());
        }
        collectionSourceRepository.save(cs);
    }

    @Override
    public void updateCollectionSource(long id, CollectionSourceUpdateDTO source) {
        CollectionSource cs = collectionSourceRepository.findOne(id);
        BeanUtils.copyProperties(source, cs);
        cs.setId(id);
        if(cs.getStatus() == CollectionSourceStatus.STARTED) {
            cs.setStartTime(new Date());
        }
        collectionSourceRepository.save(cs);
    }

    private List<CollectionSourceDTO> convertToDto(Iterable<CollectionSource> iterable) {
        List<CollectionSourceDTO> dtos = new ArrayList<>();
        for (CollectionSource cs : iterable) {
            CollectionSourceDTO dto = new CollectionSourceDTO();
            BeanUtils.copyProperties(cs, dto);
            dtos.add(dto);
        }
        return dtos;
    }
}
